import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react';
import './audio.less';

const ButtonStyle = {
  backgroundColor: 'rgba(23, 117, 245, 1)',
  borderRadius: '50%',
};

const TextStyle = {
  color: 'rgba(23, 117, 245, 1)',
};

const Backdrop = ({ activeColor, trackIndex, isPlaying }) => {
  useEffect(() => {
    document.documentElement.style.setProperty('--active-color', activeColor);
  }, [trackIndex, activeColor]);

  return <div className={`color-backdrop ${isPlaying ? 'playing' : 'idle'}`} />;
};

const AudioControls = ({ isPlaying, onPlayPauseClick, onPrevClick, onNextClick, time }) => (
  <div className="audio-controls">
    <button
      type="button"
      className="prev"
      aria-label="Previous"
      onClick={onPrevClick}
      style={TextStyle}
    >
      {time[0]}
    </button>
    {isPlaying ? (
      <button
        type="button"
        className="pause"
        onClick={() => onPlayPauseClick(false)}
        aria-label="Pause"
      >
        <PauseCircleOutlined style={ButtonStyle} />
      </button>
    ) : (
      <button
        type="button"
        className="play"
        onClick={() => onPlayPauseClick(true)}
        aria-label="Play"
      >
        <PlayCircleOutlined style={ButtonStyle} />
      </button>
    )}
    <button
      type="button"
      className="next"
      aria-label="Next"
      onClick={onNextClick}
      style={TextStyle}
    >
      {time[1]}
    </button>
  </div>
);
/*
 * Read the blog post here:
 * https://letsbuildui.dev/articles/building-an-audio-player-with-react-hooks
 */
const AudioPlayer = ({ tracks }) => {
  // State
  const [trackIndex, setTrackIndex] = useState(0);
  const [trackProgress, setTrackProgress] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [durations, setDuration] = useState(0);
  const [isDragging, setIsDragging] = useState(false); // 标记当前是否正在拖拽进度条

  // Destructure for conciseness
  const { title, artist, color, image, audioSrc } = tracks[trackIndex];

  // Refs
  const audioRef: any = useRef(new Audio(audioSrc));
  const intervalRef = useRef();
  const isReady = useRef(false);
  const [audio] = useState<any>(new Audio(audioSrc));

  // Destructure for conciseness
  const { duration } = audioRef.current;

  useEffect(() => {
    // 监听音频元数据加载完成事件，更新总时长
    audio.addEventListener('loadedmetadata', () => {
      setDuration(Math.floor(audio.duration));
    });

    // 监听音频时间更新事件，更新当前播放时间
    audio.addEventListener('timeupdate', () => {
      setCurrentTime(Math.floor(audio.currentTime));
    });

    // 移除事件监听器，避免内存泄漏
    return () => {
      audio.removeEventListener('loadedmetadata', () => {});
      audio.removeEventListener('timeupdate', () => {});
    };
  }, [audio]);

  const formatTime = (time) => {
    const minutes = Math.floor(time / 60);
    const seconds = time % 60;
    return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
  };

  const currentPercentage = duration ? `${(trackProgress / duration) * 100}%` : '0%';
  const trackStyling = `
    -webkit-gradient(linear, 0% 0%, 100% 0%, color-stop(${currentPercentage}, rgba(23, 117, 245, 1)), color-stop(${currentPercentage}, #fff))
  `;

  const handleSliderChange = (event) => {
    const newTime = parseInt(event.target.value);
    setCurrentTime(newTime);
    audio.currentTime = newTime;
  };

  // const onScrub = (value) => {
  //   // Clear any timers already running
  //   clearInterval(intervalRef.current);
  //   audioRef.current.currentTime = value;
  //   setTrackProgress(audioRef.current.currentTime);
  // };

  // const onScrubEnd = () => {
  //   // If not already playing, start
  //   if (!isPlaying) {
  //     setIsPlaying(true);
  //   }
  //   startTimer();
  // };

  // const toPrevTrack = () => {
  //   if (trackIndex - 1 < 0) {
  //     setTrackIndex(tracks.length - 1);
  //   } else {
  //     setTrackIndex(trackIndex - 1);
  //   }
  // };

  // const toNextTrack = () => {
  //   if (trackIndex < tracks.length - 1) {
  //     setTrackIndex(trackIndex + 1);
  //   } else {
  //     setTrackIndex(0);
  //   }
  // };

  // const startTimer = () => {
  //   // Clear any timers already running
  //   clearInterval(intervalRef.current);

  //   intervalRef.current = setInterval(() => {
  //     if (audioRef.current.ended) {
  //       toNextTrack();
  //     } else {
  //       setTrackProgress(audioRef.current.currentTime);
  //     }
  //   }, [1000]);
  // };

  useEffect(() => {
    if (isPlaying) {
      // audioRef.current.play();
      // startTimer();
      audio.play();
    } else {
      audio.pause();
      // audioRef.current.pause();
    }
  }, [audio, isPlaying]);

  // // Handles cleanup and setup when changing tracks
  // useEffect(() => {
  //   audioRef.current.pause();

  //   audioRef.current = new Audio(audioSrc);
  //   setTrackProgress(audioRef.current.currentTime);

  //   if (isReady.current) {
  //     audioRef.current.play();
  //     setIsPlaying(true);
  //     startTimer();
  //   } else {
  //     // Set the isReady ref as true for the next pass
  //     isReady.current = true;
  //   }
  // }, [trackIndex]);

  // useEffect(() => {
  //   // Pause and clean up on unmount
  //   return () => {
  //     audioRef.current.pause();
  //     clearInterval(intervalRef.current);
  //   };
  // }, []);

  return (
    <div className="audio-player">
      <div className="track-info">
        <div className="audio-icon">
          <img className="artwork" src={image} alt={`track artwork for ${title} by ${artist}`} />
        </div>
        <div className="audio-info">
          <h2 className="title">{title}</h2>
          <h3 className="artist">{artist}</h3>
        </div>

        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexDirection: 'column',
          }}
        >
          <input
            type="range"
            value={currentTime}
            step="1"
            min="0"
            max={duration ? duration : `${duration}`}
            className="progress"
            // onChange={(e) => onScrub(e.target.value)}
            onChange={handleSliderChange}
            // onMouseUp={onScrubEnd}
            // onKeyUp={onScrubEnd}
            style={{ background: trackStyling, marginTop: '10px' }}
          />
          <AudioControls
            isPlaying={isPlaying}
            // onPrevClick={toPrevTrack}
            // onNextClick={toNextTrack}
            time={[formatTime(currentTime), formatTime(durations)]}
            onPlayPauseClick={setIsPlaying}
          />
        </div>
      </div>
      <Backdrop trackIndex={trackIndex} activeColor={color} isPlaying={isPlaying} />
    </div>
  );
};

export default AudioPlayer;
